package artificial

import (
	"bytes"
	"fmt"
	"net/http"
	"parking-lot-go-admin/config"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/cars"
	"parking-lot-go-admin/model/park"

	"github.com/gin-gonic/gin"
)

// 进场记录列表
func EntryList(c *gin.Context) {
	requestDataMap := make(map[string]interface{})
	c.ShouldBindJSON(&requestDataMap)

	where, page, pageSize := controller.WhereStructure(requestDataMap)
	//查询信息
	var carsEntryStruct cars.CarsEntryStruct
	var carsEntryData []cars.CarsEntryStruct
	model.GetModelData(
		model.Db,
		carsEntryStruct.TableName(),
		&carsEntryData,
		model.QueryOptions{
			Page:       page,
			PageSize:   pageSize,
			Conditions: where,
			OrderBy:    "id desc",
			Debug:      true,
		},
	)

	//数据格式化
	returnData := make([]map[string]interface{}, 0)
	for _, v := range carsEntryData {
		returnData = append(returnData, map[string]interface{}{
			"id":           v.Id,
			"park_code":    v.ParkCode,
			"park_name":    v.ParkName,
			"car_number":   v.CarNumber,
			"car_no_color": v.CarNoColor,
			"in_time":      v.InTime.Format("2006-01-02 15:04:05"),
			"order_type":   v.OrderType,
			"order_no":     v.OrderNo,
			"much_id":      v.MuchId,
		})
	}

	//总数查询
	count, _ := model.CountModelData(
		model.Db,
		carsEntryStruct.TableName(),
		model.QueryOptions{
			Conditions: where,
		},
	)

	controller.Success(c,
		map[string]interface{}{
			"list":        returnData,
			"total":       count,
			"pageSize":    pageSize,
			"currentPage": page,
		})
}

// 添加进场记录
func EntryAdd(c *gin.Context) {
	requestDataStruct := struct {
		CarNumber  string `json:"car_number"`
		CarNoColor int    `json:"car_no_color"`
		ParkCode   int    `json:"park_code"`
		InTime     string `json:"in_time"`
		MuchId     string `json:"much_id"`
	}{}

	c.ShouldBindJSON(&requestDataStruct)

	var parkingLotStruct park.ParkingLotStruct
	model.GetModelDataFirst(
		model.Db,
		parkingLotStruct.TableName(),
		&parkingLotStruct,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"park_code": requestDataStruct.ParkCode,
			},
		})

	// 车辆进场
	go func() {
		//拼接url
		systemSection := config.Cfg.Section("SYSTEM")
		url := systemSection.Key("INTERFACE_URL").String() + "third/entry"

		jsonData := []byte(
			fmt.Sprintf(`{"parkCode": "%d", "parkName": "%s", "carId": "%s", "carnoColor": %d,"inTime":"%s","muchId":"%s","is_admin":1}`,
				requestDataStruct.ParkCode, parkingLotStruct.Name, requestDataStruct.CarNumber, requestDataStruct.CarNoColor, requestDataStruct.InTime, requestDataStruct.MuchId))

		fmt.Println(string(jsonData))
		//发送请求
		resp, _ := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		defer resp.Body.Close()
	}()

	controller.Success(c, "")
}
